import React, { useState, useRef, useEffect } from 'react';
import { setApiBase, getApiBase } from '@/utils/apiConfig'
import request from '@/utils/app'

interface FileItem {
  id: string;
  file: File;
  name: string;
  size: number;
  type: string;
  status: 'pending' | 'uploading' | 'success' | 'error';
  progress: number;
  errorMessage?: string;
}

// 文档列表项接口
interface DocItem {
  id: string;
  name: string;
  size: number;
  uploadTime: string;
}

// 真实接口示例
const uploadApi = async (file: File, apiUrl: string, proxyTarget: string, onProgress: (progress: number) => void): Promise<{ success: boolean; message?: string }> => {
  const formData = new FormData();
  formData.append('file', file);
  
  try {
    // 构造完整的请求URL
    // const fullUrl = proxyTarget + apiUrl;
    const fullUrl = apiUrl;
    
    const response = await fetch(fullUrl, {
      method: 'POST',
      body: formData,
    });
    // 解析 response
    const responseJson = await response.json();
    if (responseJson && responseJson?.status_code == 200) {
      return { success: true };
    } else {
      return { success: false, message: '上传失败' };
    }
  } catch (error) {
    return { success: false, message: '网络错误' };
  }
};

const UploadDemo: React.FC = () => {
  const [fileList, setFileList] = useState<FileItem[]>([]);
  const [docList, setDocList] = useState<DocItem[]>([]); // 新增文档列表状态
  const [isUploading, setIsUploading] = useState(false);
  // http://10.96.105.132:8549/api/file/upload
  const [apiUrl, setApiUrl] = useState('/api/file/upload'); // 默认API地址
  const [proxyTarget, setProxyTarget] = useState(getApiBase); // 默认代理目标
  const fileInputRef = useRef<HTMLInputElement>(null);
  const pollIntervalRef = useRef<NodeJS.Timeout | null>(null); // 轮询定时器引用

  // 在文件顶部常量定义区域添加
  const MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MB

  // 组件挂载时开始轮询，卸载时清除轮询
  useEffect(() => {
    fetchDocList(); // 立即获取一次列表
    pollIntervalRef.current = setInterval(fetchDocList, 10000); // 每10秒轮询一次
    
    return () => {
      if (pollIntervalRef.current) {
        clearInterval(pollIntervalRef.current);
      }
    };
  }, []);

  // 获取文档列表
  const fetchDocList = async () => {
    try {
      const response = await fetch('/api/doc/list');
      // 解析响应体
      const responseJson = await response.json();
      if (responseJson && responseJson?.status_code == 200) {
        setDocList(responseJson?.data);
      }
    } catch (error) {
      console.error('获取文档列表失败:', error);
    }
  };

  // 处理文件选择
  // 修改处理文件选择函数
  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    console.log(e, '---file change');

    const files = e.target.files;
    if (!files) return;
    console.log(files, '---file change');
    const newFiles: FileItem[] = [];
    const oversizedFiles: string[] = [];
    
    for (let i = 0; i < files.length; i++) {
      const file = files[i];
      
      // 检查文件大小是否超过限制
      if (file.size > MAX_FILE_SIZE) {
        oversizedFiles.push(file.name);
        continue; // 跳过超过大小限制的文件
      }
      
      newFiles.push({
        id: `${file.name}-${file.size}-${Date.now()}`,
        file,
        name: file.name,
        size: file.size,
        type: file.type,
        status: 'pending',
        progress: 0
      });
    }
  
    // 如果有超大文件，提示用户
    if (oversizedFiles.length > 0) {
      alert(`以下文件超过5MB限制，无法上传: ${oversizedFiles.join(', ')}`);
    }
  
    setFileList(prev => [...prev, ...newFiles]);
  };

  // 移除文件
  const handleRemoveFile = (id: string) => {
    setFileList(prev => prev.filter(file => file.id !== id));
  };

  // 格式化文件大小
  const formatFileSize = (bytes: number): string => {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  // 修改uploadSingleFile函数中调用uploadApi的部分
  // 上传单个文件
  const uploadSingleFile = async (fileItem: FileItem): Promise<void> => {
    return new Promise((resolve, reject) => {
      // 调用真实接口
      uploadApi(fileItem.file, apiUrl, proxyTarget, (progress) => {
        // 更新进度
        setFileList(prev => prev.map(item => 
          item.id === fileItem.id ? { ...item, progress } : item
        ));
      }).then(result => {
        if (result.success) {
          // 上传成功
          setFileList(prev => prev.map(item => 
            item.id === fileItem.id ? { ...item, status: 'success' } : item
          ));
          resolve();
        } else {
          // 上传失败
          setFileList(prev => prev.map(item => 
            item.id === fileItem.id ? { ...item, status: 'error', errorMessage: result.message } : item
          ));
          reject(new Error(result.message));
        }
      }).catch(error => {
        // 网络错误等
        setFileList(prev => prev.map(item => 
          item.id === fileItem.id ? { ...item, status: 'error', errorMessage: '网络错误' } : item
        ));
        reject(error);
      });
    });
  };

  // 批量上传文件
  const handleUpload = async () => {
    if (fileList.length === 0) return;
    console.log('走进批量上传');
    setIsUploading(true);
    
    // 过滤出需要上传的文件
    const pendingFiles = fileList.filter(file => file.status === 'pending' || file.status === 'error');
    
    // 循环调用接口上传每个文件
    for (const fileItem of pendingFiles) {
      try {
        // 更新状态为上传中
        setFileList(prev => prev.map(item => 
          item.id === fileItem.id ? { ...item, status: 'uploading' } : item
        ));
        
        // 调用上传接口
        await uploadSingleFile(fileItem);
      } catch (error) {
        console.error(`文件 ${fileItem.name} 上传失败:`, error);
        // 错误已在uploadSingleFile中处理，这里只需要continue
      }
    }
    
    setIsUploading(false);
    // 在所有文件上传完成后立即调用一次列表接口
    fetchDocList();
    // 清空上传列表
    setFileList([]);
    fileInputRef.current && (fileInputRef.current.value = '');
  };

  // 清空所有文件
  const handleClearAll = () => {
    setFileList([]);
    fileInputRef.current && (fileInputRef.current.value = '');
  };

  // 获取上传成功的文件列表
  const getSuccessFiles = () => {
    return fileList.filter(file => file.status === 'success');
  };

  return (
    <div style={{ maxWidth: '1200px', margin: '0 auto', padding: '20px' }}>
      <h2 style={{ textAlign: 'center', color: '#333' }}>后端临时：批量文件上传</h2>
      <div style={{ display: 'flex', gap: '20px' }}>
        {/* 左侧上传区域 */}
        <div style={{ flex: 1 }}>
          {/* 添加API地址和代理配置输入框 */}
          <div style={{ 
            border: '1px solid #ddd', 
            borderRadius: '8px', 
            padding: '20px', 
            marginBottom: '20px',
            backgroundColor: '#f9f9f9'
          }}>
            <h3>接口配置</h3>
            <div style={{ marginBottom: '15px' }}>
              <label style={{ display: 'block', marginBottom: '5px', fontWeight: 'bold' }}>
                API地址:
              </label>
              <input
                type="text"
                value={apiUrl}
                onChange={(e) => setApiUrl(e.target.value)}
                style={{ 
                  width: '100%', 
                  padding: '8px', 
                  border: '1px solid #ccc', 
                  borderRadius: '4px' 
                }}
                placeholder="请输入API地址，例如: /api/upload"
              />
            </div>
            <div>
              <label style={{ display: 'block', marginBottom: '5px', fontWeight: 'bold' }}>
                代理目标地址:
              </label>
              <input
                type="text"
                value={proxyTarget}
                onChange={(e) => {
                  setProxyTarget(e.target.value)
                  setApiBase(e.target.value)
                }}
                style={{ 
                  width: '100%', 
                  padding: '8px', 
                  border: '1px solid #ccc', 
                  borderRadius: '4px' 
                }}
                disabled
                placeholder="请输入代理目标地址，例如: http://10.96.105.132:8549"
              />
            </div>
          </div>
          <div style={{ 
            border: '2px dashed #ccc', 
            borderRadius: '8px', 
            padding: '30px', 
            textAlign: 'center', 
            marginBottom: '20px',
            backgroundColor: '#fafafa'
          }}>
            <input
              type="file"
              ref={fileInputRef}
              onChange={handleFileChange}
              multiple
              style={{ visibility: 'hidden'}}
            />
            <button
              onClick={() => fileInputRef.current?.click()}
              disabled={isUploading}
              style={{
                padding: '12px 24px',
                backgroundColor: '#4096ff',
                color: 'white',
                border: 'none',
                borderRadius: '4px',
                cursor: isUploading ? 'not-allowed' : 'pointer',
                fontSize: '16px'
              }}
            >
              选择文件
            </button>
            <p style={{ marginTop: '10px', color: '#666' }}>
              支持多选，可同时选择多个文件
            </p>
          </div>

          {fileList.length > 0 && (
            <div style={{ marginBottom: '20px' }}>
              <div style={{ 
                display: 'flex', 
                justifyContent: 'space-between', 
                alignItems: 'center',
                marginBottom: '10px'
              }}>
                <h3>待上传文件 ({fileList.length})</h3>
                <div>
                  <button
                    onClick={handleUpload}
                    disabled={isUploading}
                    style={{
                      padding: '8px 16px',
                      backgroundColor: '#52c41a',
                      color: 'white',
                      border: 'none',
                      borderRadius: '4px',
                      cursor: isUploading ? 'not-allowed' : 'pointer',
                      marginRight: '10px'
                    }}
                  >
                    {isUploading ? '上传中...' : '开始上传'}
                  </button>
                  <button
                    onClick={handleClearAll}
                    disabled={isUploading}
                    style={{
                      padding: '8px 16px',
                      backgroundColor: '#ff4d4f',
                      color: 'white',
                      border: 'none',
                      borderRadius: '4px',
                      cursor: isUploading ? 'not-allowed' : 'pointer'
                    }}
                  >
                    清空列表
                  </button>
                </div>
              </div>

              <div style={{ 
                maxHeight: '400px', 
                overflowY: 'auto',
                border: '1px solid #ddd',
                borderRadius: '4px'
              }}>
                {fileList.map((fileItem) => (
                  <div 
                    key={fileItem.id} 
                    style={{
                      display: 'flex',
                      alignItems: 'center',
                      padding: '12px',
                      borderBottom: '1px solid #eee'
                    }}
                  >
                    <div style={{ flex: 1 }}>
                      <div style={{ display: 'flex', alignItems: 'center' }}>
                        <span style={{ fontWeight: 'bold', marginRight: '10px' }}>
                          {fileItem.name}
                        </span>
                        <span style={{ color: '#666', fontSize: '14px' }}>
                          {formatFileSize(fileItem.size)}
                        </span>
                      </div>
                      
                      {/* 上传进度条 */}
                      {(fileItem.status === 'uploading' || fileItem.status === 'success' || fileItem.status === 'error') && (
                        <div style={{ marginTop: '8px' }}>
                          <div 
                            style={{
                              height: '6px',
                              backgroundColor: '#f0f0f0',
                              borderRadius: '3px',
                              overflow: 'hidden'
                            }}
                          >
                            <div 
                              style={{
                                height: '100%',
                                width: `${fileItem.progress}%`,
                                backgroundColor: fileItem.status === 'error' ? '#ff4d4f' : 'green',
                                transition: 'width 0.3s'
                              }}
                            />
                          </div>
                          <div style={{ 
                            display: 'flex', 
                            justifyContent: 'space-between', 
                            marginTop: '4px',
                            fontSize: '12px',
                            color: fileItem.status === 'error' ? '#ff4d4f' : '#666'
                          }}>
                            <span>
                              {fileItem.status === 'uploading' && `上传中... ${fileItem.progress}%`}
                              {fileItem.status === 'success' && '上传成功'}
                              {fileItem.status === 'error' && `上传失败: ${fileItem.errorMessage}`}
                            </span>
                          </div>
                        </div>
                      )}
                    </div>
                    
                    <button
                      onClick={() => handleRemoveFile(fileItem.id)}
                      disabled={fileItem.status === 'uploading' || isUploading}
                      style={{
                        padding: '4px 8px',
                        backgroundColor: '#ff4d4f',
                        color: 'white',
                        border: 'none',
                        borderRadius: '4px',
                        cursor: (fileItem.status === 'uploading' || isUploading) ? 'not-allowed' : 'pointer'
                      }}
                    >
                      删除
                    </button>
                  </div>
                ))}
              </div>
            </div>
          )}

          {fileList.length === 0 && !isUploading && (
            <div style={{ 
              textAlign: 'center', 
              color: '#999', 
              padding: '40px 0' 
            }}>
              暂无文件，请选择需要上传的文件
            </div>
          )}
        </div>
        
        {/* 右侧文档列表 */}
        <div style={{ flex: 1 }}>
          <div style={{ 
            border: '1px solid #ddd', 
            borderRadius: '8px', 
            padding: '20px',
            backgroundColor: '#f9f9f9'
          }}>
            <h3>文档列表 ({docList.length})</h3>
            <div style={{ 
              maxHeight: '500px', 
              overflowY: 'auto',
              border: '1px solid #ddd',
              borderRadius: '4px'
            }}>
              {docList.length > 0 ? (
                docList.map((docItem) => (
                  <div 
                    key={docItem.id} 
                    style={{
                      display: 'flex',
                      alignItems: 'center',
                      padding: '12px',
                      borderBottom: '1px solid #eee'
                    }}
                  >
                    <div style={{ flex: 1 }}>
                      <div style={{ display: 'flex', alignItems: 'center' }}>
                        <span style={{ fontWeight: 'bold', marginRight: '10px' }}>
                          {docItem.file_name}
                        </span>
                      </div>
                      <div style={{ 
                        marginTop: '4px',
                        fontSize: '12px',
                        color: '#1890ff'
                      }}>
                        状态: {docItem.file_node_start_name}
                      </div>
                      <div
                        style={{
                          fontSize: '12px',
                        }}
                      >
                        主键：{docItem.id}
                      </div>
                    </div>
                  </div>
                ))
              ) : (
                <div style={{ 
                  textAlign: 'center', 
                  color: '#999', 
                  padding: '40px 0' 
                }}>
                  暂无文档
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default UploadDemo;